package com.dongdong.config;

/**
 * @author dongdong 抖音号：W13883155245
 * @version 1.0
 * @date 2025/5/5
 * @description minio配置类
 */

import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MinioConfig {

    @Value("${spring.minio.endpoint}")
    private String endpoint;

    @Value("${spring.minio.access-key}")
    private String accessKey;

    @Value("${spring.minio.secret-key}")
    private String secretKey;

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }

    /**
     * 应用启动后自动启动 MinIO
     */
    @Bean
    public CommandLineRunner startMinioOnStartup() {
        return args -> {
            System.out.println("应用启动：正在启动 MinIO 服务...");
           // MinioProcessStarter.startMinio();
        };
    }

    /**
     * 应用关闭前自动停止 MinIO
     */
    @Bean
    public MinioShutdownHook minioShutdownHook() {
        return new MinioShutdownHook();
    }

    /**
     * MinIO 关闭钩子
     */
    public static class MinioShutdownHook implements AutoCloseable {

        @Override
        public void close() {
            System.out.println("应用关闭：正在停止 MinIO 服务...");
            //MinioProcessStarter.stopMinio();
            System.out.println("MinIO 服务已成功停止");
        }
    }
    /*public  void reset(String[] args) {

        String bucketName = "fileservice";
        MinioClient minioClient = minioClient();
        try {
            // 设置桶的权限为公共可读
            String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "/*\"]}]}";
            minioClient.setBucketPolicy(bucketName, policy);
            System.out.println("桶权限已成功设置为公共可读");
        } catch (Exception e) {
            System.out.println("发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }*/

}

